import { Stomp } from '@stomp/stompjs'
import SockJS from 'sockjs-client'

let stompClient = null
let connected = false

export function connectWebSocket(showAnnouncement: any) {
  if (connected) return

  const socket = new SockJS('http://localhost:8080/ws')
  stompClient = Stomp.over(socket)

  stompClient.connect(
    {},
    () => {
      connected = true
      console.log('WebSocket connected')

      stompClient.subscribe('/topic/announcement', (message) => {
        const announcement = JSON.parse(message.body)
        showAnnouncement(announcement)
      })
    },
    (error) => {
      console.error('WebSocket error:', error)
      connected = false
      // 尝试重新连接
      setTimeout(() => connectWebSocket(showAnnouncement), 5000)
    },
  )
}

export function disconnectWebSocket() {
  if (stompClient !== null) {
    stompClient.disconnect()
    connected = false
    console.log('WebSocket disconnected')
  }
}
